<template>
  <div class="img-box">
    <el-upload :headers="headers" :action="isDev + '/common/upload'" list-type="picture-card"
      :on-preview="handlePictureCardPreview" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
      :on-exceed="exceed" :on-remove="handleAvatarRemove" :limit="limit" :multiple="multiple" :show-file-list="true"
      :file-list="fileList">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
export default {
  props: {
    value: {
      type: String,
      default: "",
    },
    index: {
      type: Number,
      default: 0,
    },
    limit: {
      type: Number,
      default: 1,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      dialogVisible: false,
      image: null,
      //是否本地
      isDev:
        process.env.NODE_ENV === "development" ? process.env.VUE_APP_BASE_API : process.env.VUE_APP_BASE_API,
      // 图片上传请求头
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      imgArr: [],
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      valueIndex:0,
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (val) {
          this.imgArr = val.split(",");
          this.fileList = val.split(",").map((item, index) => ({ uid: index + 10000, url: this.isDev + item }));
        } else {
          this.imgArr = [];
          this.fileList = [];
        };
      },
    },
    index:{
      immediate: true,
      handler(val) {
        this.valueIndex = val;
      }
    }
  },
  created() { },
  mounted() {
  },
  methods: {
    //图片上传成功返回路径
    handleAvatarSuccess(response, file, filesList) {
      this.fileList.push({ uid: file.uid, url: this.isDev + file.response.fileName[0] });
      this.imgArr.push(file.response.fileName[0]);

      this.$emit("uploadImage", {value:this.imgArr.join(","),index:this.valueIndex});
    },
    handleAvatarRemove(file, fileList) {
      const url = file.url.slice(this.isDev.length, file.url.length);
      this.imgArr.splice(this.imgArr.indexOf(url), 1);
      this.$emit("uploadImage", {value:this.imgArr.join(","),index:this.valueIndex});
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG和png 格式!");
      };
      // const isLt2M = file.size / 1024 / 1024 < 5;
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }

      return isJPG;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /* 超出上传文件个数时 */
    exceed(file) {
      this.$message.warning("已超出上传文件个数！！！");
    },
    //图片压缩方法
    compressImg(file) {
      /* 压缩图片方法 */
      const _this = this
      return new Promise(resolve => {
        const reader = new FileReader()
        const image = new Image()
        image.onload = (imageEvent) => {
          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          const imgQuality = 0.5; //压缩图片质量
          const width = image.width * imgQuality
          const height = image.height * imgQuality
          canvas.width = width;
          canvas.height = height;
          context.clearRect(0, 0, width, height);
          context.drawImage(image, 0, 0, width, height);
          const dataUrl = canvas.toDataURL(file.type);
          const blobData = _this.dataURItoBlob(dataUrl, file.type);
          resolve(blobData)
        }
        reader.onload = (e => { image.src = e.target.result; });
        reader.readAsDataURL(file);
      });
    },
    dataURItoBlob(dataURI, type) {
      var binary = atob(dataURI.split(',')[1]);
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], { type: type });
    },
  }
};
</script>

<style scoped lang="scss"></style>
